package com.wfcm.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.wfcm.utils.UUIDGenerator;


/**
 * 阿里云分布式存储工具类
 * @author lyinlong
 *
 */
public class OSSUtil {

	//初始化client
	static OSSClient client = new OSSClient(Constants.OSS_ENDPOINT,Constants.OSS_ACCESS_ID, Constants.OSS_ACCESS_KEY);

	/**
	 * 获取指定文件夹下的文件列表
	 * @param folderName 文件夹名称(如果获取当前所有, 空字符串)
	 * @return 文件的所有key
	 * @throws IOException
	 */
	public static List<String> listBybucket(String bucketName ,String folderName) throws IOException{
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

		// 递归列出fun目录下的所有文件
		listObjectsRequest.setPrefix(folderName);

		ObjectListing listing = client.listObjects(listObjectsRequest);

		List<String> keys = new ArrayList<>();

		// 遍历所有Object
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			keys.add(objectSummary.getKey());
		}
		return keys;
	}

	/**
	 * 通过key获取指定的Object
	 * @param key
	 * @return
	 */
	public static InputStream getObject(String bucketName, String key){
		OSSObject object = client.getObject(bucketName, key);
	    InputStream objectContent = object.getObjectContent();

	    return objectContent;
	}

	/**
	 * 添加一个文件到指定文件夹
	 * @param file
	 * @param folder
	 * @return 该文件的Key(文件的唯一标识)
	 * @throws FileNotFoundException
	 */
	public static String putObject(File file , String folder , String bucketName) throws FileNotFoundException{
		 // 获取指定文件的输入流
	    InputStream content = new FileInputStream(file);

	    // 创建上传Object的Metadata
	    ObjectMetadata meta = new ObjectMetadata();

	    // 必须设置ContentLength
	    meta.setContentLength(file.length());

	    String uuid = UUIDGenerator.getUUID(false);

	    client.putObject(bucketName, folder+"/"+uuid, content, meta);

	    return uuid;
	}

	public static String putFile(URLConnection content  , String folder , String bucketName) throws IOException {
		 // 获取指定文件的输入流
	    //InputStream content = new FileInputStream(file);

	    // 创建上传Object的Metadata
	    ObjectMetadata meta = new ObjectMetadata();

	    // 必须设置ContentLength
	    /*int count = 0;
		int len = 0;
		while (count == 0) {
			count = content.available();
			len = len + count;
			System.out.println("len:"+len);
		}*/
	    long len = content.getContentLength();
		meta.setContentLength(len);
		InputStream inputStream = content.getInputStream();
		String uuid = UUIDGenerator.getUUID(false);
	    client.putObject(bucketName, folder+"/"+uuid+".jpg",inputStream , meta);

	    return folder+"/"+uuid+".jpg";
	}


	public static String putFile(InputStream content  , String folder , String bucketName) throws IOException {
		// 获取指定文件的输入流
		//InputStream content = new FileInputStream(file);

		// 创建上传Object的Metadata
		ObjectMetadata meta = new ObjectMetadata();

		// 必须设置ContentLength
		meta.setContentLength(content.available());
		String uuid = UUIDGenerator.getUUID(false);
		client.putObject(bucketName, folder+"/"+uuid+".jpg",content , meta);

		return folder+"/"+uuid+".jpg";
	}
	
	public static String addFile(Object file , String folder , String bucketName) throws IOException{
		 InputStream content  = null;
		 ObjectMetadata meta = null;
		 String  extension = "";
		if(file!=null){
			if(file instanceof CommonsMultipartFile){
				CommonsMultipartFile file1  = (CommonsMultipartFile)file;
				//文件扩展名
				 String fileName = file1.getOriginalFilename();
				 if(fileName.lastIndexOf(".")!=-1){
					 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
				 }
 				
				// 获取指定文件的输入流
				  content =file1.getInputStream();
				    // 创建上传Object的Metadata
				   meta = new ObjectMetadata();
				    // 必须设置ContentLength
				    meta.setContentLength(file1.getSize());
 				 // 设置content type  
				    String strContentType = file1.getContentType();  
				    meta.setContentType(strContentType);  
			}
			else if(file instanceof MultipartFile){
				MultipartFile	file2 = (MultipartFile)file;
				 String fileName = file2.getOriginalFilename();
				 if(fileName.lastIndexOf(".")!=-1){
					 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
				 }
				// 获取指定文件的输入流
				  content =file2.getInputStream();
				    // 创建上传Object的Metadata
				   meta = new ObjectMetadata();
				    // 必须设置ContentLength
				    meta.setContentLength(file2.getSize());
			}
			else if(file instanceof File){
				File file3 = (File)file;
				//文件扩展名
				 String fileName = file3.getName();
				 if(fileName.lastIndexOf(".")!=-1){
					 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
				 }
				
				// 获取指定文件的输入流
				  content =new FileInputStream(file3);
				    // 创建上传Object的Metadata
				  meta = new ObjectMetadata();
				    // 必须设置ContentLength
				  meta.setContentLength(file3.length());
			}
			else {
				return null;
			}
		}
	    String uuid = UUIDGenerator.getUUID(false);

	    client.putObject(bucketName, folder+"/"+uuid+extension, content, meta);

	    return folder+"/"+uuid+extension;
	}
	
	//原文件名上传
	public static String addBugFile(Object file , String folder , String bucketName) throws IOException{
		 InputStream content  = null;
		 ObjectMetadata meta = null;
		 String  extension = "";
		 String  fileName = "";
		if(file!=null){
			if(file instanceof CommonsMultipartFile){
				CommonsMultipartFile file1  = (CommonsMultipartFile)file;
				//文件扩展名
				 fileName = file1.getOriginalFilename();
				 if(fileName.lastIndexOf(".")!=-1){
					 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
				 }
				
				// 获取指定文件的输入流
				  content =file1.getInputStream();
				    // 创建上传Object的Metadata
				   meta = new ObjectMetadata();
				    // 必须设置ContentLength
				    meta.setContentLength(file1.getSize());
				 // 设置content type  
				    String strContentType = file1.getContentType();  
				    meta.setContentType(strContentType);  
			}
			else if(file instanceof MultipartFile){
				MultipartFile	file2 = (MultipartFile)file;
				 fileName = file2.getOriginalFilename();
				 if(fileName.lastIndexOf(".")!=-1){
					 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
				 }
				// 获取指定文件的输入流
				  content =file2.getInputStream();
				    // 创建上传Object的Metadata
				   meta = new ObjectMetadata();
				    // 必须设置ContentLength
				    meta.setContentLength(file2.getSize());
			}
			else if(file instanceof File){
				File file3 = (File)file;
				//文件扩展名
				 fileName = file3.getName();
				 if(fileName.lastIndexOf(".")!=-1){
					 extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
				 }
				
				// 获取指定文件的输入流
				  content =new FileInputStream(file3);
				    // 创建上传Object的Metadata
				  meta = new ObjectMetadata();
				    // 必须设置ContentLength
				  meta.setContentLength(file3.length());
			}
			else {
				return null;
			}
		}
	    String uuid = UUIDGenerator.getUUID(false);

	    client.putObject(bucketName, folder+"/"+uuid+"_"+fileName, content, meta);

	    return folder+"/"+uuid+"_"+fileName;
	}
	
    /** 
     * 下载文件 
     * @param client 
     * @param bucketName 
     * @param key 
     * @param filename 
     * @throws OSSException 
     * @throws ClientException 
     */  
    public static void downloadFile(OSSClient client, String bucketName, String key, String filename)  
            throws OSSException, ClientException {  
        client.getObject(new GetObjectRequest(bucketName, key),  
                new File(filename));  
    }  
	
	/**
	 * 删除指定的文件
	 * @param key
	 */
	public static void delete(String key,String bucketName){

		client.deleteObject(bucketName, key);
	}

	/**
	 * 新建文件桶
	 * @param bucketName
	 */
	public static void createBucket(String bucketName){
		client.createBucket(bucketName);
	}

}
